import 'package:get/get.dart';

import '../http/request_api.dart';
import '../model/base_response.dart';
import '../model/contract_list_model.dart';
import '../model/contract_model.dart';
import '../model/user_contract_model.dart';
import 'base_api_service.dart';
import 'user_storage_service.dart';

class HomeService extends BaseApiService {
  static final HomeService _instance = HomeService._internal();

  factory HomeService() {
    return _instance;
  }

  HomeService._internal();

  /// 获取首页数据
  Future<BaseResponse<Map<String, dynamic>>> getHomeData() async {
    return await post<Map<String, dynamic>>(
      RequestApi.GET_HOME_DATA,
      showLoading: false,
      fromJsonT: (data) => data as Map<String, dynamic>,
    );
  }

   /// 获取合约列表
  Future<BaseResponse<ContractListResponse>> getContractList() async {
    return await post<ContractListResponse>(
      RequestApi.GET_CONTRACT_LIST,
      data: {
        "page": 1,
        "page_size": 20,
      },
      showLoading: false,
      fromJsonT: (json) => ContractListResponse.fromJson(json),
    );
  }

   /// 获取我的合约列表
  Future<BaseResponse<UserContractResponse>> getUserContractList() async {
    final uid = UserStorageService().getUserId();
    if (uid?.isEmpty ?? true) {
      throw Exception('login_required'.tr);
    }
    
    return await post<UserContractResponse>(
      RequestApi.GET_USER_CONTRACT_LIST,
      // data: {
      //   // "xtest": "1024CxNqmt0LTa4IckJ",
      // },
      fromJsonT: (json) => UserContractResponse.fromJson(json),
    );
  }

  /// 创建广告合约
  Future<BaseResponse<Map<String, dynamic>>> createAdsContract(Map<String, dynamic> params) async {
    return await post<Map<String, dynamic>>(
      RequestApi.CREATE_ADS_CONTRACT,
      data: params,
      showLoading: true,
      fromJsonT: (data) => data as Map<String, dynamic>,
    );
  }

  /// 购买合约
  Future<BaseResponse<Map<String, dynamic>>> purchaseContract({
    required String contractId,
    required String contractType,
    Map<String, dynamic>? additionalParams,
  }) async {
    final data = {
      'contract_id': contractId,
      'contract_type': contractType,
      ...?additionalParams,
    };
    
    return await post<Map<String, dynamic>>(
      '/contracts/purchase', // 假设的购买接口
      data: data,
      showLoading: true,
      fromJsonT: (data) => data as Map<String, dynamic>,
    );
  }
}